$NG.AllReady(function (
  page,
  { useDataIndexChange, useValuesChange, useClick, useBeforeClick,useUpdateRows, useUpdateRow }
) {
  if (page.oType == "add") {
    cntMFilter()
}
  const mstform = $NG.getCmpApi("p_form_ywgcwb_pay");
  const dgir1 = $NG.getCmpApi("p_form_ywgcwb_pay_d1");
  const dgir2 = $NG.getCmpApi("p_form_ywgcwb_pay_d2");
  const billno = $NG.getCmpApi("p_form_ywgcwb_pay").getItem("bill_no").getValue();
  console.log("获取到数据", billno);

  // getCntCount("p_form_ywgcwb_pay","u_main_cnt",()=>{
  //     getYfInfo();
  //     getCntInfo();
  //     getZbdAmtByCnt()
  //     getFbyfAmtInfo()
  // })
  function setTitle() {
    const cnt_name = (String(mstform.getItem("u_main_cnt").getText()) || 0)
    const dt = (String(mstform.getItem("u_apply_dt").getValue()) || 0)
    $NG.updateState((updater) => {
        updater.data.p_form_ywgcwb_pay.setProps({
            bill_name: `${cnt_name}${dt}分包应付单`
        })
    })
}
useBeforeClick(()=>{
  if(!oneTable.getItem('u_js_type').getValue()){
      $NG.alert("请先选择分包结算类型！")
      return false
  }
},"p_form_ywgcwb_pay_d1.imp")
  if(page.oType == 'add'){
      $NG.updateState((updater) => {
          updater.data.p_form_ywgcwb_pay.setProps({
            phid_fcur: {
              label: "人民币",
              value: 1,
            },
            exchangerate: 1,
            u_fbhtyfk:0,
            u_fbljkpje:0,
            u_main_cnt_ykpje:0,
            u_bckpje:0
          });
        });
  }
  //隐藏表头、表体单据引用    
$NG.getCmpApi("toolbar_top").getItem('imp').setHidden();
const gridToolbar = $NG.getCmpApi("toolbar_p_form_ywgcwb_pay_d1")
gridToolbar.getItem('imp').setProps({children:'引用分包结算单'})
$NG.getCmpApi("toolbar_p_form_ywgcwb_pay_d2").getItem('imp').setHidden();

  async function getToken() {
    const token = await $NG.request.post({
      url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/authenticationFi",
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 token 成功:", token);
    return token;
  }

  async function getEventCode() {
    const eventCode = await $NG.request.post({
      url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/getEventCode",
      // url: "https://inner-apisix.hisense.com/sd/sd/Fi/sdToFi/fiIntegration/getEventCode?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6",
      data: JSON.stringify({ bill_no: billno }),
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 eventCode 成功:", eventCode);
    return eventCode;
  }
  //添加按钮
  $NG.getCmpApi("toolbar_p_form_ywgcwb_pay_d2").insert({
    id: "sendBtn",
    text: "获取发票信息",
    iconCls: "icon-New",
  });

  useClick(async function ({ args }) {
    console.log("点击了获取发票信息按钮");
    const identifytype = billno; // 页面唯一标识（根据实际需求设置）
    const token = await getToken();
    const eventCode = await getEventCode();

    // 修正 WebSocket URL
    const socketUrl = "wss://fi-uat.hisense.com/ierp/msgwatch/";

    // 初始化 WebSocket
    const socket = new WebSocket(
      `${socketUrl}?identifytype=${encodeURIComponent(
        identifytype
      )}&token=${encodeURIComponent(token)}&listenerType=RimWebSocketListener`
    );

    // WebSocket 打开事件
    socket.onopen = () => {
      console.log("WebSocket 连接已建立:", new Date());
      var url = "https://fi-uat.hisense.com/ierp/";
      var viewfpUrl =
        url + "index.html?formId=rim_fpzs_main&eventCode=" + eventCode;
      var encodeUrl = encodeURIComponent(viewfpUrl, "utf-8");
      var requestUrl =
        url +
        "accessTokenLogin.do?encode=true&access_token=" +
        token +
        "&redirect=" +
        encodeUrl;
      window.open(requestUrl);
      socket.send("来自客户端的消息: " + location.href + " - " + new Date());
    };

    // WebSocket 收到消息事件
    socket.onmessage = (event) => {
      console.log("收到服务器消息:", event.data); // 输出服务器返回的消息
      const data = JSON.parse(event.data);
      const invoiceData = data.invoiceData;
    
      // 获取表体当前的所有行数据
      const existingRows = $NG.getCmpApi("p_form_ywgcwb_pay_d2").getRows();
    
      // 创建一个Set，用于快速判断表体中是否存在某发票号
      const existingInvoiceNos = new Set(existingRows.map((row) => row.u_fphm));
    
      // 定义存储新数据的数组
      var gridArr = [];
    
      // 判断 invoiceData 是否存在，并获取长度
      const gridCount = invoiceData ? invoiceData.length : 0;
      if (gridCount > 0) {
        for (let i = 0; i < gridCount; i++) {
          const invoice = invoiceData[i];
          const items = invoice.items[0];
          // 判断发票号是否已存在于表体中
          if (existingInvoiceNos.has(invoice.invoiceNo)) {
            console.log(`发票号 ${invoice.invoiceNo} 已存在于表体中，跳过此条数据`);
            continue; // 跳过重复数据
          }
    
          // 如果发票号未重复，则加入到gridArr中
          var gridObj = {
            u_fplx: invoice.invoiceType,
            u_serial_no: invoice.serialNo,
            u_invoicecode: invoice.invoiceCode,
            u_fphm: invoice.invoiceNo,
            u_kq_dt: invoice.invoiceDate,
            u_rate: items.taxRate,
            u_check_code: invoice.checkCode,
            u_saler_name: invoice.salerName,
            u_saler_taxno: invoice.salerTaxNo,
            u_saler_addressph: invoice.salerAddressPhone,
            u_saler_account: invoice.salerAccount,
            u_buyer_name: invoice.buyerName,
            u_buyer_taxno: invoice.buyerTaxNo,
            u_buyer_addressph: invoice.buyerAddressPhone,
            u_buyer_account: invoice.buyerAccount,
            u_invoice_amt: invoice.invoiceAmount,
            u_total_tax_amt: invoice.totalTaxAmount,
            u_amt_vat_total: invoice.totalAmount,
            u_remarks: invoice.remark,
            u_machine_no: invoice.machineNo,
            u_drawer: invoice.drawer,
            u_reviewer: invoice.reviewer,
            u_payee: invoice.payee,
            u_invoice_sta: invoice.invoiceStatus,
            u_expend_sta: invoice.expendStatus,
            u_rk_dt: invoice.billCreateTime,
            u_check_sta: invoice.checkStatus,
            u_invalid_dt: invoice.invalidDate,
            u_type: invoice.type,
            u_ori_invoice_code: invoice.originalInvoiceCode,
            u_ori_invoice_no: invoice.originalInvoiceNo,
            u_download_url: invoice.downloadUrl,
            u_file_type: invoice.fileType,
            u_if_revise: invoice.isRevise,
            u_snapshot_url: invoice.snapshotUrl,
            u_errcode: invoice.errcode,
            u_description: invoice.description,
            u_validate_mes: invoice.validateMessage,
            u_msg: invoice.msg,
            u_name: invoice.name,
            u_config_type: invoice.configType,
            u_config: invoice.config,
            u_key: invoice.key,
          };
          gridArr.push(gridObj);
        }
    
        // 如果有新数据，插入到表体中
        if (gridArr.length > 0) {
          dgir2.addRows(gridArr);
          console.log("新增的数据:", gridArr);
        } else {
          console.log("没有需要插入的新数据。");
        }
      } else {
        console.log("没有发票数据！");
      }
    };

    // WebSocket 关闭事件
    socket.onclose = (event) => {
      console.log("WebSocket 连接已关闭:", new Date());
      if (event.code !== 1000) {
        // 非正常关闭
        console.error(
          "连接异常关闭，错误代码:",
          event.code,
          "原因:",
          event.reason
        );
      }
    };

    // WebSocket 错误事件
    socket.onerror = (error) => {
      console.error("WebSocket 错误:", error);
    };

    // 防止内存泄漏，组件卸载时关闭 WebSocket
    return () => {
      if (socket.readyState === WebSocket.OPEN) {
        socket.close();
      }
    };
  }, "sendBtn");
  // $("#sendBtn").click(function() {
  //     function getChanges() {
  //         var identifytype = phid; // 页面唯一标识，如拼接 billid 和 resource
  //         var token = getToken().then(token =>{
  //             console.log("获取token成功:", token);
  //             return token;
  //         }); // 登录接口获取的 access token
  //         var socketUrl = "ws://https://fi-uat.hisense.com/ierp/"; // WebSocket 服务器地址，替换为实际地址

  //         // 初始化 WebSocket 对象
  //         var socket = new WebSocket(socketUrl + "/msgwatch/?identifytype=" + encodeURIComponent(identifytype) +
  //                                    "&token=" + encodeURIComponent(token) +
  //                                    "&listenerType=RimWebSocketListener");

  //         // WebSocket 打开事件
  //         socket.onopen = function() {
  //             console.log("WebSocket 连接已建立:", new Date());
  //             socket.send("来自客户端的消息: " + location.href + " - " + new Date());
  //         };

  //         // WebSocket 收到消息事件
  //         socket.onmessage = function(event) {
  //             console.log("收到服务器消息:", event.data); // 输出服务器返回的消息
  //         };

  //         // WebSocket 关闭事件
  //         socket.onclose = function(event) {
  //             console.log("WebSocket 连接已关闭:", new Date());
  //             if (event.code !== 1000) { // 非正常关闭
  //                 console.error("连接异常关闭，错误代码:", event.code, "原因:", event.reason);
  //             }
  //         };

  //         // WebSocket 错误事件
  //         socket.onerror = function(error) {
  //             console.error("WebSocket 错误:", error);
  //         };
  //     }

  //     // 调用 WebSocket 函数
  //     getChanges();
  // });
  if (page.oType == "add") {
      mstform.getItem('u_bczfsyje').setValue(0)
    $NG.updateState((updater) => {
      updater.data.p_form_ywgcwb_pay.setProps({
        u_apply_dt: formatDate(new Date(), "yyyy-mm-dd"),
      });
    });
  }
  const oneTable = $NG.getCmpApi("p_form_ywgcwb_pay");
  useValuesChange(({ args }) => {
    console.log(`监听的项目选择`, args);
    const id = args[0].phid_pc?.phid_pc ? args[0].phid_pc?.pc_no : "";
    console.log(`项目id`, id);
    // 通过项目id获取项目信息
    getProjectInfo();
    // 过滤合同
    cntMFilter();
      getCntCount("p_form_ywgcwb_pay","u_main_cnt",()=>{
      getYfInfo();
      getCntInfo();
      getZbdAmtByCnt()
      getFbyfAmtInfo()
      setTitle()
  })
  }, "p_form_ywgcwb_pay.phid_pc");
  // 监听合同编码的选择
  useValuesChange(({ args }) => {
    console.log(`合同编码监听信息`, args);
    setTimeout(() => {
      cntMFilter();
      getYfInfo();
      getCntInfo();
      getZbdAmtByCnt()
      getFbyfAmtInfo()
      setTitle() 
    }, 300);
  }, "p_form_ywgcwb_pay.u_main_cnt");

  useValuesChange(({args})=>{
      getSuppyInfo()
  },"p_form_ywgcwb_pay.u_payee")


  function getProjectInfo() {
    console.log(`项目phid_pc`, oneTable.getItem("phid_pc").getValue());
    $NG.execServer(
      "getPtInfoByPhid",
      { phid: oneTable.getItem("phid_pc").getValue() },
      (res) => {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(`项目jsonINfo`, datas);
        $NG.updateState((updater) => {
          updater.data.p_form_ywgcwb_pay.setProps({
            u_pc_no: datas.pc_no,
            u_division: {
              value: datas.division_phid,
              label: datas.division_name,
            },
            u_regional_center: {
              value: datas.regional_center_phid,
              label: datas.regional_center_name,
            },
            u_product_line: {
              //产品线
              value: datas.midwife_phid,
              label: datas.midwife_name,
            },
          });
        });
      }
    );
  }

  //合同根据项目ID过滤
  function cntMFilter() {
    $NG.updateUI((updater, state) => {
        console.log("过滤参数检查", updater);
        updater.fieldSetForm.p_form_ywgcwb_pay.u_main_cnt.setProps({
            onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi("p_form_ywgcwb_pay").getItem("phid_pc").getValue();
                if (!phid_pc) {
                    $NG.alert("请先选择项目");
                    return false;
                } else {
                    return true;
                }
            },
            ...(!!$NG.getCmpApi("p_form_ywgcwb_pay").getItem("phid_pc").getValue() && {
                clientSqlFilter: {
                    'pcm3_cnt_m.phid_pc': $NG.getCmpApi("p_form_ywgcwb_pay").getItem("phid_pc").getValue(),
                },
            }),
        });
    });
}

  function getCntInfo() {
    console.log(`合同id`, oneTable.getItem("u_main_cnt").getValue());
    if (!oneTable.getItem("u_main_cnt").getValue()) return;
    $NG.execServer(
      "getCntMInfoByPhid",
      { phid: oneTable.getItem("u_main_cnt").getValue() },
      (res) => {
        console.log(res);
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log("通过合同id获取的信息", datas);
        $NG.updateState((updater) => {
          updater.data.p_form_ywgcwb_pay.setProps({
            u_main_cnt_no: datas.pcm_no,
            u_fbht_amt: datas.cnt_sum_vat_fc,
            u_product_line: {
              label: datas.midwife_name ? datas.midwife_name : "",
              value: datas.midwife_phid ? datas.midwife_phid : "",
            },
            u_supply: {
              label: datas.supply_name,
              value: datas.supply_id,
            },

            u_payee:{
              label: datas.supply_name,
              value: datas.supply_id,
            },
            u_pay_org:{
              label:datas.customer_name,
              value:datas.customer_id
            },
            u_fbywlx: {
              label: datas.pct_name,
              value: datas.pct_id,
            },
          });
        });
        // 延迟获取供应商信息
        setTimeout(()=>{
          getSuppyInfo()
        },300)
      }
    );
  }
  useValuesChange(({args})=>{
      dgir1.getRows().forEach(item=>{
          item.u_zfbl = $NG.getCmpApi("p_form_ywgcwb_pay").getItem("u_fbljkpzb").getValue()
            item.u_bq_apply_je = (Number(item.u_bjsdje) || 0) * (Number(item.u_zfbl) || 0);
      })
      dgir1.refreshView()
  },"p_form_ywgcwb_pay.u_fbljkpzb")
  useUpdateRow(({ args }) => {
    const _data = args[0];
  }, "p_form_ywgcwb_pay_d1");

  let __timeId = 0;
  useUpdateRows(({ args }) => {
    console.log("更新数据1", args[0])
    if (__timeId) {
      clearTimeout(__timeId);
    }
    __timeId = setTimeout(() => {
      const total_amt = 0
      args[0].forEach((item) => {
        item.u_bq_apply_je =
          (Number(item.u_bjsdje) || 0) * (Number(item.u_zfbl) || 0);
          // item.u_zfbl = (Number((Number(item.u_bq_apply_je) || 0) / (Number(item.u_bjsdje) || 0)) || 0);
          if(item.u_bq_apply_je > item.u_bjsdje){
              $NG.alert("本期申请金额不得大于结算金额，请重新填写！")
              item.u_bq_apply_je = 0
              item.u_zfbl = 0
          }
          if((Number(item.u_bq_apply_je) || 0) > (Number(item.u_remain_amt) || 0)){
              $NG.alert(`本期申请金额不得大于剩余金额，请重新填写！`)
              item.u_bq_apply_je = 0
          }
      });
      
      dgir1.refreshView();
    }, 200);
  }, "p_form_ywgcwb_pay_d1");

  //监听发票信息表
  useUpdateRows(({ args }) => {
    console.log("更新数据2", args[0]);
    reduceTable2(args[0]);
    dgir2.refreshView();
  }, "p_form_ywgcwb_pay_d2");
  function reduceTable2(rows) {
    // 发票金额
    let u_amt = 0;
    // 税额
    let u_tax_amt = 0;
    // 价税合计
    let u_amt_vat_total = 0;
    rows.forEach((item, index) => {
      u_amt += item.u_amt_vat_total ? item.u_amt_vat_total : 0;
      u_tax_amt += item.u_total_tax_amt ? item.u_total_tax_amt : 0;
    });
    $NG.updateState((updater) => {
      updater.data.p_form_ywgcwb_pay.setProps({
        u_bckpje: u_amt,
        u_yksje: u_tax_amt,
      });
    });
  }
  //监听付款信息表
  useUpdateRows(({ args }) => {
    console.log("更新数据1", args[0]);
    reduceTable1(args[0]);

    dgir1.refreshView();
  }, "p_form_ywgcwb_pay_d1");
  function reduceTable1(rows) {
    // 未付金额
    let u_ahtyfqfje = 0;
    // 申请金额
    let u_bq_apply_je = 0;
    let hd_total_amt = 0
    rows.forEach((item, index) => {
      if (!item.u_bz) {
        item.u_bz = 1;
        item.u_bz_EXName = "人民币";
      }
      if(!item.u_zfbl){
          item.u_zfbl = oneTable.getItem("u_fbljkpzb").getValue();
      }
      u_ahtyfqfje += (Number(item.u_ahtyfqfje) || 0) 
      u_bq_apply_je += (Number(item.u_bq_apply_je) || 0)
      hd_total_amt += (Number(item.u_hd_amt) || 0)
    });
    $NG.updateState((updater) => {
      updater.data.p_form_ywgcwb_pay.setProps({
        u_main_cnt_ykpje: u_ahtyfqfje,
        u_bcsqfkje: u_bq_apply_je,
        u_hdzf_amt:hd_total_amt
      });
    });
    if (page.oType == 'add') {
      $NG.updateState((updater) => {
          updater.data.p_form_ywgcwb_pay.setProps({
              u_bczfsyje: u_bq_apply_je
          });
      });
      
  }
  }
  // 获取款项信息
  function getYfInfo() {
    $NG.execServer(
      "getTkCnt",
      { phid: oneTable.getItem("u_main_cnt").getValue() },
      function (res) {
        console.log(res);
        if (res.count == 0) return;
        const _data = JSON.parse(res.data)[0].extendObjects;
        console.log(`获取款项信息`, _data);
        $NG.updateState((updater) => {
          updater.data.p_form_ywgcwb_pay.setProps({
            u_fbljkpzb: _data.a_zfbfb,
            u_zfjsjs: _data.a_jsjs,
            u_pay_stage: {
              label: _data.a_name,
              value: _data.a_phid,
            },
          });
        });
      }
    );
  }
  //监听申请金额
  useValuesChange(({ args }) => {
    console.log(`申请金额监听`, args);
  }, "p_form_ywgcwb_pay.u_bcsqfkje");
    //监听申请金额
  useValuesChange(({ args }) => {
    console.log(`付款类型监听`, args);
    getFBCntPayDetailInfo()
  }, "p_form_ywgcwb_pay.u_fk_type");

  function getFBCntPayDetailInfo(){
    const u_fk_type = mstform.getItem("u_fk_type").getVlaue()
    if(!u_fk_type) return 
    $NG.execServer("getFBCntPayDetailInfo",{phid:u_fk_type},(res)=>{
        if(res.count == 0) return
        const datas = JSON.parse(res.data)[0].extendObjects
        $NG.updateState(updater=>{
          updater.fieldSetForm.p_form_ywgcwb_pay.setProps({
            u_fbljkpzb:datas.bal_percent,
            u_zfbl:datas.user_zfjs_fnth,
            
          })
        })
    })
  }
  // { //添加按钮
  //     $NG.getCmpApi('toolbar_p_form_ywgcwb_pay_d2').insert({
  //         id: "scfq",
  //         text: "上传发票",
  //         iconCls: "icon-New"
  //     });
  // }
  // { //添加按钮
  //     $NG.getCmpApi('toolbar_p_form_ywgcwb_pay_d2').insert({
  //         id: "lqfq",
  //         text: "拉取发票",
  //         iconCls: "icon-New"
  //     });
  // }
  // useClick(async function ({ args }) {
  //     alert('上传发票成功')
  // }, "scfq");
  // useClick(async function ({ args }) {
  //     alert('拉取发票成功')
  // }, "lqfq");
  // 计算2个日期之间得天数
  function formatDate(dateStr, outputFormat) {
    const date = new Date(dateStr);

    if (isNaN(date)) {
      return "无效的日期字符串";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");

    let formattedDate;

    switch (outputFormat) {
      case "yyyy-mm-dd":
        formattedDate = `${year}-${month}-${day}`;
        break;
      case "yyyy-mm-dd HH:mm":
        formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
        break;
      // 可以根据需要继续添加其他格式的处理逻辑
      default:
        formattedDate = "不支持的输出格式";
    }

    return formattedDate;
  }
      var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
    tabPanel[1].addEventListener("click", function () {
        console.log("tab2被点击了");
        setTimeout(() => {
            if (page.oType == "add") {
                $NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
                $NG.alert("请先保存主表数据");
                tabPanel[0].click();
            }
        }, 200);
    });
  // 获取当前支付单合同累计审批金额
 // getZbdAmtByCnt()
  function getZbdAmtByCnt(){
      const cnt = mstform.getItem("u_main_cnt").getValue();
      if(!cnt) return
      $NG.execServer("getZbdAmtByCnt", {cnt: cnt}, (res)=>{
          console.log(`支付单`,res);
          if(res.count == 0) return 
          const _data =  JSON.parse(res.data)[0].extendObjects
          $NG.updateState((updater)=>{
              updater.data.p_form_ywgcwb_pay.setProps({
                  u_fbhtyfk:(Number(_data.amt) || 0)
              })

          })
      })
  }

  // 获取分包应付单相应累计金额
  //getFbyfAmtInfo()
  function getFbyfAmtInfo(){
      const cnt = mstform.getItem("u_main_cnt").getValue();
      if(!cnt) return
      $NG.execServer("getFbyfAmtInfo", {cnt: cnt}, (res)=>{
          console.log(`累计金额`,res);
          if(res.count == 0) return 
          const _data = JSON.parse(res.data)[0].extendObjects
          $NG.updateState((updater)=>{
              updater.data.p_form_ywgcwb_pay.setProps({
                  u_fbljkpje:(Number(_data.kpamt) || 0),
                  u_main_cnt_ykpje:_data.sqamt
              })
          })
      })
  }

// 获取供应商银行信息
function getSuppyInfo(){
  const phid = mstform.getItem("u_payee").getValue()
  if(!phid) return 
  $NG.execServer("getSuppyInfo", { phid }, (res) => {
      console.log(`查询供应商信息`,res);
      if(res.count == 0) return 
      const _data = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater)=>{
          updater.data.p_form_ywgcwb_pay.setProps({
              u_bank_no: _data.user_yhzh,
              u_rece_bank:{
                  label:_data.user_bank_name,
                  value:_data.bphid
              }
          })
      })
  })
}


});



//获取合同数量
function getCntCount(table, key, fun) {
  if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
  $NG.execServer("getCntCount", { type: 4, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
    switch (res.count) {
      case 0:
        return;
      case 1:
        const datas = JSON.parse(res.data)[0].extendObjects;
        const temp_map = {};
        temp_map[key] = datas.phid;
        temp_map[`${key}_EXName`] = datas.bill_name;
        $NG.updateState((updater) => {
          updater.data[table].setProps({
            ...temp_map,
          });
          setTimeout(() => {
            if (fun) {
              fun();
            }
          }, 200);
        });
    }
  });
}
